import React, { useState } from "react";
import PropTypes from "prop-types";
import classNames from "classnames";

const typeMap = {
  success: "bg-green-400 border border-green-500 px-4 py-2 text-xs",
  error: "bg-red-400 border border-red-500 px-4 py-2 text-xs",
  info: "bg-blue-400 border border-blue-500 px-4 py-2 text-xs",
  warning: "bg-yellow-400 border border-yellow-500 px-4 py-2 text-xs",
}

const Alert = ({
  message,
  description,
  visible = true,
  type = 'info',
  closable,
  ...reset
}) => {
  const [_visible, setVisible] = useState(visible)
  const onClose = () => setVisible(false)
  if (!_visible) {
    return null
  }

  const classString = classNames('relative', typeMap[type])
  const closeIconClassString = classNames('absolute bg-transparent font-semibold leading-none right-0 top-0 outline-none focus:outline-none opacity-50 hover:opacity-75 hover:text-black',
    {
      'px-5 py-3 text-2xl': description,
      'px-4 py-2 text-base': !description,
    }
  )

  return (
    <div className={classString} {...reset}>
      <div className={closable ? 'mr-8' : ''}>
        <div className={description ? 'text-base' : 'text-xs'}>{message}</div>
        <div>{description}</div>
      </div>
      {closable && <button onClick={onClose} className={closeIconClassString}>x</button>}
    </div>
  )
}

Alert.propTypes = {
  message: PropTypes.string,
  description: PropTypes.string,
  visible: PropTypes.bool,
  type: PropTypes.oneOf([
    'success',
    'error',
    'info',
    'warning',
  ]),
  closable: PropTypes.bool,
}

export default Alert